#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>
#import <objc/runtime.h>

#import "FWPopupView.h"
#import "FWCommon.h"


static const CGFloat kFrameIndent = 30;
static const CGFloat kMessageInset = 20;

static const NSTimeInterval kPopupTime = 1.5;
static const NSTimeInterval kInstructionTime = 5.0;


@implementation FWPopupView

@synthesize label, displayTime;


+ (void)displayPopupMessage:(NSString*)msg forView:(UIView*)view color:(UIColor*)color font:(UIFont*)font duration:(NSTimeInterval)duration dismiss:(BOOL)dismiss
{
    if (view.superview)
        view = view.superview;
    
    CGRect frame = view.frame;
    frame.size.width -= (kFrameIndent + kMessageInset) * 2;
    
    CGSize textSize = [msg sizeWithFont:font constrainedToSize:frame.size lineBreakMode:UILineBreakModeWordWrap];

    frame.size.width = textSize.width + kMessageInset * 2;
    frame.size.height = textSize.height + kMessageInset * 2;
    frame.origin.x = (view.frame.size.width - frame.size.width) / 2;
    frame.origin.y = (view.frame.size.height - frame.size.height) / 2;
    
    if ([view respondsToSelector:@selector(contentOffset)]) {
        CGPoint offset = [(UIScrollView*)view contentOffset];
        frame.origin.y += offset.y;
    }
    
    CGRect textFrame = CGRectMake((frame.size.width - textSize.width) / 2,
                                  (frame.size.height - textSize.height) / 2,
                                  textSize.width, textSize.height);

    FWPopupView* popup = [[FWPopupView alloc] initWithFrame:frame];
    popup.userInteractionEnabled = dismiss;
    popup.label.frame = textFrame;
    popup.label.font = font;
    popup.label.text = msg;
    popup.displayTime = duration;
    
    if (color)
        popup.layer.backgroundColor = [color colorWithAlphaComponent:0.9].CGColor;

    popup.alpha = 0.0f;
    popup.transform = CGAffineTransformConcat(CGAffineTransformIdentity, CGAffineTransformMakeScale(0.01f, 0.01f));
    [view addSubview:popup];
    [view bringSubviewToFront:popup];

    [UIView beginAnimations:nil context:view];
    [UIView setAnimationDelegate:popup];
    [UIView setAnimationDuration:0.30];
    [UIView setAnimationDidStopSelector:@selector(showAnimationFinished:finished:context:)];
    popup.transform = CGAffineTransformConcat(CGAffineTransformIdentity, CGAffineTransformIdentity);
    popup.alpha = 1.0f;
    [UIView commitAnimations];
}

+ (void)displayPopupMessage:(NSString*)msg color:(UIColor*)color forView:(UIView*)view
{
    [FWPopupView displayPopupMessage:msg
                             forView:view
                               color:color
                                font:[UIFont boldSystemFontOfSize:[UIFont systemFontSize] * 2]
                            duration:kPopupTime
                             dismiss:NO];
}

+ (void)displayPopupMessage:(NSString*)msg forView:(UIView*)view
{
    [FWPopupView displayPopupMessage:msg 
                             forView:view
                               color:nil
                                font:[UIFont boldSystemFontOfSize:[UIFont systemFontSize] * 2]
                            duration:kPopupTime
                             dismiss:NO];
}

+ (void)displayPopupInstruction:(NSString*)msg forView:(UIView*)view
{
    [FWPopupView displayPopupMessage:msg
                             forView:view
                               color:nil
                                font:[UIFont boldSystemFontOfSize:[UIFont systemFontSize] * 1.2]
                            duration:kInstructionTime
                             dismiss:YES];
}


// ******************************************************************************************
#pragma mark -
#pragma mark Initialisation and object management

- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7f];
        self.layer.cornerRadius = kMessageInset;
        self.layer.masksToBounds = NO;
        self.layer.shadowOffset = CGSizeMake(2, 5);
        self.layer.shadowOpacity = 0.5f;
        
        self.label = [[[UILabel alloc] initWithFrame:frame] autorelease];
        self.label.backgroundColor = [UIColor clearColor];
        self.label.textColor = [UIColor whiteColor];
        self.label.textAlignment = UITextAlignmentCenter;
        self.label.lineBreakMode = UILineBreakModeWordWrap;
        self.label.numberOfLines = 0;
        self.label.opaque = NO;

        [self addSubview:self.label];
    }
    
    return self;
}

- (void)dealloc
{
    [label release];
    
    [super dealloc];
}


// ******************************************************************************************
#pragma mark -
#pragma mark Close after time elapsed

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self finished:nil];
}

- (void)showAnimationFinished:(NSString *)animationID finished:(BOOL)finished context:(void*)context
{
    [self performSelector:@selector(finished:)
               withObject:(UIView*)context
               afterDelay:displayTime 
                  inModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
}

- (void)hideAnimationFinished:(NSString *)animationID finished:(BOOL)finished context:(void*)context
{
    [self removeFromSuperview];
    [self release];
}

- (void)finished:(UIView *)parent
{
    if (!finished) {
        finished = YES;
        
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDidStopSelector:@selector(hideAnimationFinished:finished:context:)];
        [UIView setAnimationDuration:0.30];
        self.transform = CGAffineTransformConcat(CGAffineTransformIdentity, CGAffineTransformMakeScale(0.01f, 0.01f));
        [UIView commitAnimations];
    }
}

@end
